package com.sniff.atp.constant.config;

import com.sniff.atp.provider.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.constant.config
 * @Author: zxy
 * @CreateTime: 2024-01-26 16:46
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource dataSourceOne() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource dataSourceTwo() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.purchase")
    public DataSource dataSourceThree() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.beework")
    public DataSource dataSourceFour() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();

        dynamicDataSource.setDefaultTargetDataSource(dataSourceOne());
        Map<Object, Object> dsMap = new HashMap<>();
        dsMap.put("master", dataSourceOne());
        dsMap.put("slave", dataSourceTwo());
        dsMap.put("purchase", dataSourceThree());
        dsMap.put("beework", dataSourceFour());

        dynamicDataSource.setTargetDataSources(dsMap);

        return  dynamicDataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dynamicDataSource());
    }
}
